package cn.tomoya.module.security;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class ValidatorUtil
{
    static Validator validator;
    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     * 调用validator对model进行格式校验 <br/>
     * @param obj 要校验的model
     * @return null，表示正常；否则表示校验有问题
     */
    public static <T> String validate(T obj) {
        Set<ConstraintViolation<T>> set = validator.validate(obj);

        if (set != null && set.size() != 0) {
            StringBuffer sb = new StringBuffer();
            for (ConstraintViolation<T> c : set) {
                // 字段和对应的错误信息
                sb.append(c.getPropertyPath() + " " + c.getMessage() + ";");
            }
            return sb.toString();
        }
        return null;
    }

    public static Validator getValidator() {
        return validator;
    }
}
